package com.davioliveira.cantalk.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.ess.wifi_direct.model.Msg;
import com.google.gson.Gson;

public class MensagemDAO {
	private SQLiteDatabase database;
	private OpenHelper dbHelper;

    public static final String TABLE_NAME = "mensagem";
    public static final String MSG = "msg";
    public static final String REM = "rem";
    public static final String DEST = "dest";

	private String[] allColumns = {MSG, REM, DEST};

	public MensagemDAO(Context context) {
		dbHelper = new OpenHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
		database.close();
		database = null;
	}

	public long insert(String rem, String dest, ArrayList<Msg> msgs) {
		long lastID = 0;
		for (Msg msg : msgs) {
			ContentValues values = new ContentValues();
			values.put(REM, rem);
			values.put(DEST, dest);
			values.put(MSG, new Gson().toJson(msg));
			lastID = database.insert(TABLE_NAME, null, values);
		}
		return lastID;
	}

	public boolean deleteHistorico(String rem, String dest) {
		String where = REM + " = '" + rem + "' AND " + DEST + " = '" + dest + "'";
		long wReturn = database.delete(TABLE_NAME, where, null);
		if(wReturn == 0) {
			return false;
		} else {
			return true;
		}
	}

	public ArrayList<Msg> read(String rem, String dest) {
		String where = REM + " = '" + rem + "' AND " + DEST + " = '" + dest + "'";
		ArrayList<Msg> msgs = new ArrayList<Msg>();
		
		Cursor c = database.query(TABLE_NAME, allColumns, where, null,null, null, null); 
		if(c.moveToFirst())
			do{
				int indexMsg = c.getColumnIndex(MSG);
				msgs.add(new Gson().fromJson(c.getString(indexMsg), Msg.class));
			}while(c.moveToNext());
		
		return msgs;
	}
	
}
